import React, { useContext, useEffect, useRef, useState } from 'react';
import type { InputRef } from 'antd';
import { Button, Form, Input, Popconfirm, Table } from 'antd';
import { useNavigate } from 'react-router-dom'
import type { FormInstance } from 'antd/es/form';
import { getCustomFrom, setCustomFrom, delCustomFrom, getNavigationId } from '@/request/basicSettings'

const EditableContext = React.createContext<FormInstance<any> | null>(null);

interface Item {
    nid?: React.Key;
    describe?: string;
    type?: string;
    name?: string;
}

interface EditableRowProps {
    index: number;
}

const EditableRow: React.FC<EditableRowProps> = ({ index, ...props }) => {
    const [form] = Form.useForm();
    return (
        <Form form={form} component={false}>
            <EditableContext.Provider value={form}>
                <tr {...props} />
            </EditableContext.Provider>
        </Form>
    );
};

interface EditableCellProps {
    title: React.ReactNode;
    editable: boolean;
    children: React.ReactNode;
    dataIndex: keyof Item;
    record: Item;
    handleSave: (record: Item) => void;
}

const EditableCell: React.FC<EditableCellProps> = ({
    title,
    editable,
    children,
    dataIndex,
    record,
    handleSave,
    ...restProps
}) => {
    const [editing, setEditing] = useState(false);
    const inputRef = useRef<InputRef>(null);
    const form = useContext(EditableContext)!;

    useEffect(() => {
        if (editing) {
            inputRef.current!.focus();
        }
    }, [editing]);

    const toggleEdit = () => {
        setEditing(!editing);
        form.setFieldsValue({ [dataIndex]: record[dataIndex] });
    };

    const save = async () => {
        try {
            const values = await form.validateFields();

            toggleEdit();
            handleSave({ ...record, ...values });
        } catch (errInfo) {
            console.log('Save failed:', errInfo);
        }
    };
    let childNode = children;
    if (editable) {
        childNode = editing ? (
            <Form.Item
                style={{ margin: 0 }}
                name={dataIndex}
                rules={[
                    {
                        required: true,
                        message: `${title} is required.`,
                    },
                ]}
            >
                <Input ref={inputRef} onPressEnter={save} onBlur={save} />
            </Form.Item>
        ) : (
            <div className="editable-cell-value-wrap" style={{ paddingRight: 24 }} onClick={toggleEdit}>
                {children}
            </div>
        );
    }
    return <td {...restProps}>{childNode}</td>;
};

type EditableTableProps = Parameters<typeof Table>[0];

interface DataType {
    nid?: React.Key;
    name?: string;
    type?: string;
    describe?: string;
}

type ColumnTypes = Exclude<EditableTableProps['columns'], undefined>;

const settleIn: React.FC = () => {
    const navigate = useNavigate()
    const [dataSource, setDataSource] = useState<DataType[]>([]);
    const defaultColumns: (ColumnTypes[number] & { editable?: boolean; dataIndex: string })[] = [
        {
            title: '窗体名称',
            dataIndex: 'name',
            width: '30%',
            editable: true,
            render: (text: string) => {
                return <span>{text ? text : '/'}</span>
            }
        },
        {
            title: '描述',
            dataIndex: 'describe',
            editable: true,
            render: (text: string) => {
                return <span>{text ? text : '/'}</span>
            }
        },
        {
            title: '表单类型',
            dataIndex: 'type',
            editable: true,
            render: (text: string) => {
                return <span>{text ? text : '/'}</span>
            }
        },
        {
            title: '操作',
            dataIndex: '',
            key: 'op',
            render: (record: { id: React.Key }) => {
                return <div>
                    <Popconfirm title="Sure to delete?" onConfirm={() => handleDelete(record)}>
                        <a style={{ marginRight: '10px' }}>Delete</a>
                    </Popconfirm>
                    {
                        record.id ? <a onClick={() => handleEdit(record)}>edit</a> : ''
                    }
                </div>
            }

        },
    ];
    useEffect(() => {
        getCustom()
    }, [])

    const getCustom = async () => {
        const res = await getCustomFrom()
        setDataSource(res.data)
    }
    const handleEdit = (record: any) => {
        navigate('/home/basicSettings/customFrom', {
            state: {
                id: record.id,
                nid: record.nid
            }
        })
    }
    const handleDelete = async (record: any) => {
        if (!record.id) {
            const newData = dataSource.filter((x: any) => x.nid !== record.nid)
            setDataSource(newData)
            return
        }
        const res = await delCustomFrom(record.nid)
        if (res.status == 200) {
            getCustom()
        }
    };
    const handleAdd = async () => {
        const { data } = await getNavigationId()
        const addInfo = [...dataSource, { nid: data }]
        setDataSource(addInfo)
    };
    const handleSave = async (row: DataType) => {
        await setCustomFrom(row)
        getCustom()
    };

    const components = {
        body: {
            row: EditableRow,
            cell: EditableCell,
        },
    };

    const columns = defaultColumns.map((col) => {
        if (!col.editable) {
            return col;
        }
        return {
            ...col,
            onCell: (record: DataType) => ({
                record,
                editable: col.editable,
                dataIndex: col.dataIndex,
                title: col.title,
                handleSave,
            }),
        };
    });
    return (
        <div>
            <div className='flex flex-jc-fe'>
                <Button onClick={handleAdd} type="dashed" style={{ marginBottom: 16 }}>
                    添加窗体
                </Button>
            </div>
            <Table
                components={components}
                rowClassName={() => 'editable-row'}
                bordered
                dataSource={dataSource}
                rowKey='nid'
                columns={columns as ColumnTypes}
            />
        </div>
    );
};
export default settleIn;